#include <stdio.h>
#include <stdlib.h>
#include "stack_link.h"


//初始化栈
int Init_Stack(link_head **ptr)
{
	*ptr = malloc(sizeof(**ptr));	
	if(*ptr == NULL)
		return -1;
	(*ptr)->first = NULL;
	(*ptr)->top = NULL;
	(*ptr)->number = 0;
		return 0;
}

//销毁栈
void Destroy_Stack(link_head *ptr)
{
	Clear_Stack(ptr);
	free(ptr);
}

//栈清空
void Clear_Stack(link_head *ptr)
{
	if(ptr == NULL || ptr->first == NULL)
		return ;

	stack_st *p = ptr->top;
	stack_st *q = NULL;
	for(;p;p = q)
	{
		q = p->prev;
		free(p);
		ptr->number--;
	}

}

//判断栈是否为空
int IsEmpty_Stack(link_head *ptr)
{
	if(ptr==NULL || ptr->number == 0 || ptr->top == NULL)
		return 1;
	else
		return 0;
}

//栈的长度
int Length_Stack(link_head *ptr)
{
	if(ptr == NULL)
		return 0;
	return ptr->number;
}

//出栈
int Pop_Stack(link_head *ptr,Datatype *data)
{
	if(ptr == NULL || ptr->number == 0)
		return -1;
	stack_st *p = ptr->top;
	stack_st *q = p->prev;
	ptr->top = p->prev;
	p->prev = NULL;
	if(ptr->top)
	{	
		ptr->top->next = NULL;
	}
	*data = p->data;
	free(p);
	ptr->number--;
	if(ptr->number == 0)
	{
		ptr->first = NULL;
	}
/*
	if(p == ptr->first)
	{
		ptr->first = NULL;
		ptr->top = NULL;
		*data = p->data;
		free(p);
		ptr->number--;
		return 0;
	}

	ptr->top = q;
	*data = p->data;
	free(p);
	ptr->number--;
*/	
	return 0;
}

//入栈
int Push_Stack(link_head *ptr,Datatype data)
{
	if(ptr == NULL)
		return -1;
	stack_st *newnode = NULL;
	newnode = malloc(sizeof(*newnode));
	if(newnode == NULL)
		return -1;
	newnode->data = data;
	newnode->prev = NULL;
	newnode->next = NULL;

	if(ptr->top == NULL)
	{
		ptr->first = newnode;
		ptr->top = newnode;

	}
	else
	{
		newnode->prev = ptr->top;
		ptr->top->next = newnode;
		ptr->top = newnode;
	}
	ptr->number++;
		return 0;
}

//获得栈顶元素
int GetTop_Stack(link_head *ptr,Datatype *data)
{
	if(ptr == NULL || ptr->number == 0)
		return -1;
	*data = ptr->top->data;
		return 0;
}
